
set(port_ $ENV{ARDUINO_PORT})
if (NOT port_)
    set(port_ ${ARDUINO_PORT})
endif()

find_program(AVROBJCOPY "avr-objcopy")
find_program(AVRDUDE "avrdude")

# convert a bin to a flashable .hex file.
# TODO: make it so that it finds ${name_} in the CMAKE_RUNTIME_OUTPUT_DIRECTORY?
function(hex name_)
  if( NOT name_ )
    message(FATAL_ERROR "function( hex ) missing arguments...!")
  endif()
  add_custom_target(${name_}.hex)  #not gonna work hex and hex?
  add_dependencies(${name_}.hex ${name_})

  add_custom_command(TARGET ${name_}.hex POST_BUILD
    COMMAND ${AVROBJCOPY} -O ihex -R .eeprom ${name_} ${name_}.hex
    )
endfunction()

# Flash a file to your Arduino!
# TODO: make it so that it finds ${name_}.hex in the CMAKE_RUNTIME_OUTPUT_DIRECTORY?
# TODO: fix the name.  It should not be flash_f()
# TODO: add "PORT /dev/whatever" as an option...
function(arduino_generate_flash name_)
  if( NOT port_)
    message(FATAL_ERROR "Missing ARDUINO_PORT.  Set in CMake or environment and retry.")
    set(port_ "/dev/ttyACM0")
  endif()
  hex(${name_})
  add_custom_target(flash)  #not gonna work flash and flash?
  set(hex_name ${name_}.hex)
  add_dependencies(flash ${hex_name})

  #/usr/bin/avrdude -P /dev/ttyACM0 -b 115200 -c stk500v1 -p m328p -V -F -U flash:w:rtc-play.hex:i
  add_custom_command(TARGET flash POST_BUILD
    COMMAND ${AVRDUDE} -P ${port_} -b ${ARDUINO_${ARDUINO_PLATFORM}_UPLOAD_SPEED} -c ${ARDUINO_${ARDUINO_PLATFORM}_UPLOAD_PROTOCOL} -p ${ARDUINO_${ARDUINO_PLATFORM}_BUILD_MCU} -V -F -U flash:w:${hex_name}:i
    )
endfunction()

add_custom_target(reset)
add_custom_command(TARGET reset POST_BUILD
    COMMAND echo 0 > ${PORT}
)


macro(generate_arduino_flash name_)
  arduino_generate_flash( ${name_} )
  message(WARNING "generate_arduino_flash is deprecated.  Please update your CMakeLists.txt file to use arduino_generate_flash.")
endmacro()
